package com.apes.fn.server.servicePlan.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.fn.crm.customer.FnCustomer;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.jpa.tuple.date.DateTime;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.model.CarLabel;
import com.apes.scm.masterdata.car.model.CarModel;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.*;

/**
 * Creator: czs
 * CreateDate: 2023-08-02 10:55:28
 * Description: 报价单
 **/
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = QuotationOrder.CONST_TABLE_NAME, indexes = {
        @Index(columnList = "source_plan")
})
public class QuotationOrder extends Model {
    public static final String CONST_TABLE_NAME = "ser_quotation_order";
    public static final String CONST_INNER_SOURCE_SERVICEPLAN = "servicePlan";
    public static final String CONST_INNER_SOURCE_WORKORDER = "workOrder";

    @Id
    @Column(name = "id", nullable = false, length = 24)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "报价单编码",  padding = 5 , prefix = "QO%(company)%(yy)%(month)", useDateRange=true)
    private String id;

    @Column(name = "source_plan", length = 20)
    @Comment("来源方案")
    private String sourcePlan; //来源方案

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fn_customer_expand_id", referencedColumnName = "id")
    @Comment("赋能客户车辆扩展信息")
    private FnCustomerExpand fnCustomerExpand;

    @Column(name = "car_liscence", length = 255)
    @Comment("车牌（作并发锁用）")
    private String carLiscence; //车牌

    @Column(name = "realname", length = 32)
    @Comment("客户名称")
    private String realname;

    @Column(name = "mobile", length = 32)
    @Comment("客户手机号")
    private String mobile;

    public void setMobile(String mobile) {
        if (mobile.length()!=11)throw new RuntimeException("手机号不足11位,请检查");
        this.mobile = mobile;
    }

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "quotation_order_date")
    @Comment("单位报价日期")
    private Date quotationOrderDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;  //单据所属公司

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "belong_dept_id", referencedColumnName = "id", nullable = false)
    @Comment("方案门店")
    private Dept belongDept;  //区分，该单据属于哪个门店，权限用

    @Column(name = "belong_Dept_Name", length = 255)
    @Comment("方案门店")
    private String belongDeptName;

    @Column(name = "customer_unit", length = 255)
    @Comment("车主单位")
    private String customerUnit;

    @Column(name = "customer_remarks", length = 1000)
    @Comment("车主备注")
    private String customerRemarks;

    @Column(name = "dept_remark", length = 1000)
    @Comment("门店备注")
    private String deptRemark;


    @States(name = "方案状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "delete", name = "删除"),
            @State(id = "apply", name = "审核")
    })
    @Column(name = "state", length = 32, nullable = false)
    private String state ;


    @Column(name = "sales_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("方案结算金额")
    private double salesAmount = 0;  //工时费 + 配件 ，不包含管理费等其他 [同意服务标记为真的都计算]

    @Column(name = "balance_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("方案结算金额")
    private double balanceAmount = 0;  //工时 + （领用数量-归还数量   *   优惠单价）  【同意服务的 + 非终止的】
    public double getBalanceAmount(){
        return caculateBalanceAmount();
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_uid", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apply_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole applyUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "apply_date")
    @Comment("审核日期")
    private Date applyDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "estimated_delivery_date")
    @Comment("预计交车时间")
    private Date estimatedDeliveryDate;

    public String getGetCarInfo() {
//        if (this.getCarInfo==null)return "--";
        return getCarInfo;
    }

    @Column(name = "getCarInfo", length = 250)
    @Comment("接车信息")
    private String getCarInfo ;


    @Column(name = "get_Car_Type", length = 256)
    @Comment("接车类型")
    private String getCarType;

    @Column(name = "pick_Car_Id", length = 36)
    @Comment("接车单号")
    private String pickCarId;

    @Column(name = "pick_Car_Type", length = 36)
    @Comment("接车单据类型")
    private String pickCarType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "car_configuration_id", referencedColumnName = "id")
    @Comment("车型配置")
    private CarConfiguration carConfiguration;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "car_model_id", referencedColumnName = "id")
    @Comment("车型")
    private CarModel carModel;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "car_label_id", referencedColumnName = "id")
    @Comment("厂牌")
    private CarLabel carLabel;


    @OneToMany(mappedBy = "quotationOrder", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<QuotationWorkItems> quotationWorkItems = new ArrayList<QuotationWorkItems>(); //从表
    public List<QuotationWorkItems> getQuotationWorkItems(){
        for(QuotationWorkItems quotationWorkItem : quotationWorkItems){
            quotationWorkItem.setQuotationOrder(this);
        }
        return quotationWorkItems;
    }

    public void setQuotationWorkItems(List<QuotationWorkItems> quotationWorkItems){
        if (quotationWorkItems == null)  quotationWorkItems = new ArrayList<QuotationWorkItems>();
        this.quotationWorkItems.clear();
        this.quotationWorkItems.addAll(quotationWorkItems);
    }

    @OneToMany(mappedBy = "quotationOrder", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<QuotationFittingsItems> quotationFittingsItems = new ArrayList<QuotationFittingsItems>(); //从表
    public List<QuotationFittingsItems> getQuotationFittingsItems(){
        for(QuotationFittingsItems fittingsItems : quotationFittingsItems){
            fittingsItems.setQuotationOrder(this);
        }
        return quotationFittingsItems;
    }

    public void setQuotationFittingsItems(List<QuotationFittingsItems> quotationFittingsItems){
        if (quotationFittingsItems == null)  quotationFittingsItems = new ArrayList<QuotationFittingsItems>();
        this.quotationFittingsItems.clear();
        this.quotationFittingsItems.addAll(quotationFittingsItems);
    }

    @Transient
    private PartyRole _creator;

    public List<QuotationOrderItems> getServicePlanItems() {
         servicePlanItems = new ArrayList<>();
        if (getQuotationFittingsItems()!=null)servicePlanItems.addAll(getQuotationFittingsItems());
        if (getQuotationWorkItems()!=null)servicePlanItems.addAll(getQuotationWorkItems());
        return servicePlanItems;
    }

    public void setServicePlanItems(List<QuotationOrderItems> servicePlanItems) {
        this.servicePlanItems = servicePlanItems;
    }

    @Transient
    private List<QuotationOrderItems> servicePlanItems;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }
    @Transient
    private FnCustomer _customer;

    @Transient
    private Map customer;
    public Map getCustomer() {
        if (fnCustomerExpand == null || fnCustomerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", fnCustomerExpand.getRealname(),
                "mobile", fnCustomerExpand.getMobile(),
                "level", fnCustomerExpand.getCustomerLevelId(),
                "vendorCode", fnCustomerExpand.getVendorCode(),
                "userRole", MapUtil.mapper(
                        "id", fnCustomerExpand.getUserRoleId(),
                        "name", fnCustomerExpand.getUserRoleName()
                )
        );
    }

    @Transient
    private Map customerCar;
    public Map getCustomerCar() {
        if (fnCustomerExpand == null || fnCustomerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", fnCustomerExpand.getCarLicense(),
                "customer", this.getCustomer(),
                "vendorCode", fnCustomerExpand.getVendorCode(),
                "jekunModelCode",fnCustomerExpand.getJekunModelCode(),
                "vin", fnCustomerExpand.getVin(),
                "unitClient",MapUtil.mapper(
                        "clientCode",fnCustomerExpand.getUnitClientId()
                )
        );
    }

    private double caculateBalanceAmount(){
        if(this.servicePlanItems == null) return 0;
        double balanceAmount = 0;
        for(QuotationOrderItems servicePlanItem : this.servicePlanItems){
            balanceAmount += servicePlanItem.balanceAmount();
        }
        return balanceAmount;
    }


    @Transient
    private Integer serviceStateFlag = 1;

    public Double getSalesAmountShow() {
//        if (this.submissionDate!=null)return this.salesAmount;
        return getAllSalesAmount();
    }

    @Transient
    private Double salesAmountShow;

    public Double getAllSalesAmount() {
        return this.getServicePlanItems().stream().mapToDouble(QuotationOrderItems::getSalesAmount).sum();
    }

    @Transient
    private Double allSalesAmount;


    @Transient
    private double workAmountShow;
    public double getWorkAmountShow(){
        return this.getQuotationWorkItems().stream()
                .mapToDouble(QuotationOrderItems::getSalesAmount).sum();
    }

    @Transient
    private double partAmountShow;
    public double getPartAmountShow(){
        return this.getQuotationFittingsItems().stream()
                .mapToDouble(QuotationOrderItems::getSalesAmount).sum();
    }

//    @Transient
//    private double commissionAmountShow;
//    public double getCommissionAmountShow(){
//        return getServicePlanItems().stream()
//                .mapToDouble(i -> Arith.mul(i.getSaleQty() ,i.getEstimatedCommission())).sum();
//    }


    @Transient
    private Map fnCustomerExpandTemp;
    public Map getFnCustomerExpandTemp(){
        return this.getCustomerCar();
    }
    @Transient
    private boolean promptConfirm = false;

    @Transient
    private int chooseWarehouse = 0;

    public boolean isAutoDispatchProcess() {
        if (autoDispatchProcess){
            autoDispatchProcess = false;
            return true;
        }
        return false;
    }

    @Transient
    private boolean autoDispatchProcess = false;

    @Transient
    private String pageName = "none";

    public String getCarModelTemp() {
        String temp = "";
        if (carModel!=null)temp = temp + carModel.getName()+" ; ";
        if (carLabel!=null)temp = temp + "厂牌: " + carLabel.getName()+" ; ";
        if (carConfiguration!=null)temp = temp + "配置车型: " +  carConfiguration.getName();
        return temp;
    }

    @Transient
    private String carModelTemp ;

    public String getEstimatedDeliveryDateTemp() {
        if (estimatedDeliveryDate==null)return null;
        String format = DateUtil.format(this.estimatedDeliveryDate, DateUtil.SHOW_DATE_FORMAT);
        return format;
    }

    @Transient
    private String estimatedDeliveryDateTemp ;

    /**
     * 计算明细上的主表合计金额
     */
    public void computeSum(){
        double salesAmount = 0; //销售金额，当确认日期为空，都进行统计（方案确认后，这个金额不进行统计）
        double sumManagementCost = 0;//销售金额，当确认日期为空，都进行统计（方案确认后，这个金额不进行统计）
        double balanceAmount = 0 ;//方案确认不为空，质检日期不为空，结算日期为空的时候，进行操作都统计
        double referTaxPlan = 0;
        setItemDetail();
        for(QuotationOrderItems servicePlanItem : getServicePlanItems()){
            salesAmount += servicePlanItem.getSalesAmount();
            balanceAmount += servicePlanItem.balanceAmount();
        }
        this.salesAmount = Arith.round(salesAmount,2);
        this.balanceAmount = Arith.round(balanceAmount,2);
    }

    /**
     * 计算明细上的相关信息
     */
    public void setItemDetail(){
        for(QuotationOrderItems servicePlanItem : getServicePlanItems()){
            if(servicePlanItem.getSaleQty() <= 0)
                throw new RuntimeException(servicePlanItem.getProductName() + "商品销售数不能小于等于0");

            if(servicePlanItem.getPftPriceUnit() <= 0)
                throw new RuntimeException(servicePlanItem.getProductName() + "商品销售金额不能小于等于0");

            if(servicePlanItem.getPrimaryPriceUnit() <= 0)
                throw new RuntimeException(servicePlanItem.getProductName() + "商品销售金额不能小于等于0");

            if( servicePlanItem.getSalesAmount() <= 0)
                throw  new RuntimeException(servicePlanItem.getProductName() + "商品金额有误，请检查后提交");

            //单品销售金额
            servicePlanItem.setSalesAmount(
                    servicePlanItem.getSaleQty() * servicePlanItem.getPftPriceUnit()
            );
            //折扣率
            if(servicePlanItem.getPrimaryPriceUnit() !=0) servicePlanItem.setDiscountRate(
                    servicePlanItem.calculateDiscountRate()
            );

        }
    }

}
